package com.itelite.controller;

import com.itelite.aop.WinControllerPointCut;
import com.itelite.common.info.Result;
import com.itelite.common.util.RandomUtils;
import com.itelite.common.util.SecurityUtils;
import com.itelite.domain.pojo.User;
import com.itelite.domain.pojo.Validate;
import com.itelite.handler.ValidateHandler;
import com.itelite.service.UserService;
import com.itelite.service.ValidateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author 沈洋 邮箱:1845973183@qq.com
 * @create 2021/8/2-22:43
 **/
@Api("用户模块")
@RestController
@RequestMapping("/user/api")
@Slf4j
public class UserController {
    @Value("${front.server.ip}")
    private String frontServerIp;
    @Autowired
    private UserService userService;
    @Autowired
    private ValidateService validateService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Value("${spring.mail.username}")
    private String from;
    @ApiOperation("修改密码")
    @PostMapping("/updatePassword")
    public Result updatePassword(@RequestBody Map<String,String> map){
        Result result = null;
        String oldPassword = map.get("oldPassword");
        String newPassword = map.get("newPassword");
        if(StringUtils.isEmpty(oldPassword)||StringUtils.isEmpty(newPassword)) return Result.failure("参数不完整");
        String password = userService.queryUserPassword(SecurityUtils.getUserId());
        if(!passwordEncoder.matches(oldPassword, password)){
            result = Result.failure("原密码错误");
        }else {
            if (userService.updatePassword(SecurityUtils.getUserId(),newPassword)>0) {
                result = Result.success("重置密码成功");
            }else result = Result.failure("重置密码失败，请稍后重试！");
        }
        return result;
    }
    @ApiOperation("申请邮箱重置密码")
    @GetMapping("/auth/applyRestPassword/{email}")
    public Result applyRestPassword(@PathVariable String email, HttpServletRequest request){
        List<User> users = userService.queryUserByEmail(email);
        Result result = null;
        if (users == null){
            result = Result.failure("该邮箱所属用户不存在");
        }else {
            if (validateService.sendValidateLimitation(email, 5,1)){
                // 若允许重置密码，则在pm_validate表中插入一行数据，带有token
                Validate validate = new Validate();
                User user = users.get(0);
                log.info("申请重置密码的用户：{}"+user.getRealName());
                validate.setUserId(user.getUserId());
                validate.setEmail(user.getEmail());
                validate.setResetToken(UUID.randomUUID().toString());
                validate.setType("passwordReset");
                validate.setCreateDate(new Date());
                validate.setModifyDate(new Date());
                validateService.insertNewResetRecord(validate);
                // 设置邮件内容
                String appUrl = request.getScheme() + "://" + frontServerIp;
                SimpleMailMessage passwordResetEmail = new SimpleMailMessage();
                passwordResetEmail.setFrom(from);
                passwordResetEmail.setTo(email);
                passwordResetEmail.setSubject("【IT培优】忘记密码");
                passwordResetEmail.setText("您正在申请重置密码，请点击此链接重置密码: \n" + appUrl + "/resetPassword?token=" + validate.getResetToken());
                validateService.sendPasswordResetEmail(passwordResetEmail);
                result= Result.success("发送成功");
            }else {
                result = Result.failure("操作过于频繁，请稍后再试！");
            }
        }
        return result;
    }
    /**
     * 将url的token和数据库里的token匹配，成功后便可修改密码，token有效期为60分钟
     */
    @ApiOperation(value = "重置密码", notes = "重置密码")
    @PostMapping(value = "/auth/resetPassword")
    public Result resetPassword(@RequestBody HashMap<String,Object>map){
        Result result = null;
        if(!ValidateHandler.catchErrors(map,"token","password").equals(ValidateHandler.VALIDATE_SUCCESS)){
            result = Result.failure("缺少参数");
        }
        // 通过token找到validate记录
        List<Validate> validates = validateService.findUserByResetToken((String) map.get("token"));
        if (validates == null){
            result = Result.failure("该重置请求不存在");
        }else {
            Validate validate = validates.get(0);
            if (validateService.validateLimitation(validate.getEmail(), Long.MAX_VALUE, 30, (String) map.get("token"))){
                Integer userId = validate.getUserId();
                userService.updatePassword(userId,(String) map.get("password"));
                result = Result.success("密码重置成功");
            }else {
                result = Result.failure("该连接已失效");
            }
        }
        return result;
    }
    @ApiOperation("重置邮箱")
    @WinControllerPointCut
    @GetMapping("/resetEmail/{token}")
    public Result resetEmail(@PathVariable String token){
        Result result = null;
        List<Validate> validates = validateService.findUserByResetToken(token);
        if(CollectionUtils.isEmpty(validates)){
            result=Result.failure("重置请求不存在");
        } else {
            Validate validate = validates.get(0);
            userService.updateUserEmail(validate.getUserId(),validate.getEmail());
            result = Result.success("重置成功");
        }
        return result;
    }

    @ApiOperation("验证邮箱是否存在")
    @GetMapping("/auth/validateEmail/{email}")
    public Result validateEmail(@PathVariable String email){
        if (userService.validateEmail(email)) {
            return Result.success().data("status",200);
        }return Result.success().data("status",500);
    }

    @ApiOperation("获取个人信息")
    @GetMapping("/personalInfo")
    @WinControllerPointCut
    public Result getPersonalInfo(){
        return Result.success().data("userInfo",userService.queryUserVo(SecurityUtils.getUserId()));
    }
    @ApiOperation("申请重置邮箱")
    @GetMapping("/applyResetEmail/{email}")
    public Result getEmailCode(@PathVariable String email){
        List<User> users = userService.queryUserByEmail(email);
        Result result = null;
        if(!CollectionUtils.isEmpty(users)){
            result = Result.failure("该邮箱已绑定账号"+users.get(0).getUsername());
        }else {
            if (validateService.sendValidateLimitation(email, 5,1)){
                // 若允许更改邮箱，则在pm_validate表中插入一行数据，带有token
                Validate validate = new Validate();
                User user = users.get(0);
                validate.setUserId(user.getUserId());
                validate.setEmail(user.getEmail());
                String token = RandomUtils.getRandom(6)+"";
                validate.setResetToken(token);
                validate.setType("emailReset");
                validate.setCreateDate(new Date());
                validate.setModifyDate(new Date());
                validateService.insertNewResetRecord(validate);
                // 设置邮件内容
                SimpleMailMessage passwordResetEmail = new SimpleMailMessage();
                passwordResetEmail.setFrom(from);
                passwordResetEmail.setTo(email);
                passwordResetEmail.setSubject("【IT培优】修改邮箱");
                passwordResetEmail.setText("亲爱的用户"+user.getRealName()+":您好!\n\n"+"您收到这封电子邮件是因为您 (也可能是某人冒充您的名义) 申请了修改邮箱。假如这不是您本人所申请, 请不用理会这封电子邮件, 但是如果您持续收到这类的信件骚扰, 请您尽快联络管理员。\n" +
                        "\n" +
                        "   请使用以下验证码完成后续修改邮箱流程\n" +
                        "   \n"+token+"     \n");
                validateService.sendPasswordResetEmail(passwordResetEmail);
                result= Result.success("发送成功");
            }else {
                result = Result.failure("操作过于频繁，请稍后再试！");
            }
        }
        return result;
    }
}
